package config

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *Orm

type Orm struct {
	*gorm.DB
}

//Gorm初始化方法
func OrmInit() {
	//读取配置文件相关信息
	database := Config.Section("database")

	user, err := database.GetKey("User")
	if err != nil {
		panic(err.Error())
	}
	passwd, err := database.GetKey("Password")
	if err != nil {
		panic(err.Error())
	}
	host, err := database.GetKey("Host")
	if err != nil {
		panic(err.Error())
	}
	dbName, err := database.GetKey("Name")
	if err != nil {
		panic(err.Error())
	}

	//格式化
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", user, passwd, host, dbName)

	//panic(dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		//打印执行的SQl语句
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err.Error())
	}

	orm := new(Orm)
	orm.DB = db
	DB = orm

}
